package com.nubia.utils;
import io.jsonwebtoken.*;
import java.util.Date;
import java.util.UUID;

/**
 * token 生成工具类
 */
public class JwtUtils {
    //有效时间计算 为30分钟
    private final static long time = 1000 * 60 * 60*24;
    //签名
    private final static String signature = "eyJ0eWUiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
            ".eyJ1c2VybmFtZSI6ImFkbWluIiwicm9sZSI6ImFkbWluIiwic3ViIjoiYWNjZXNzLWhlYWRlciIsImV4cCI6MTYzNjU0Nzg0NywianRpIjoiZGY1MTk5YjEtMzQxYy00NGViLTk5MTUtZmRiYTcxODU1ZTQ3In" +
            "0.jJQ0ykRPB8Owrjy9QeTVUK2gxrisE7K0jBzOJWSt4TM";

    /**
     * 生成token
     *
     * @return
     */
    public static String creatToken(String userid) {
        //创建一个新的jwt 生成token
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //设置头部 信息
                //type jwt
                //算法 HS256
                .setHeaderParam("tye", "JWT")
                .setHeaderParam("alg", "HS256")
                //设置payload
                .claim("userid", userid)
                .setSubject("access-header")
                //set vail time
                .setExpiration(new Date(time + System.currentTimeMillis()))
                //set only id uuid
                .setId(UUID.randomUUID().toString())
                //set signature
                .signWith(SignatureAlgorithm.HS256, signature)
                //拼接三部分 合成token
                .compact();
        return jwtToken;
    }

    /**
     * 校验token是否合法
     *
     * @param token
     * @return
     */
    public static boolean analysisToken(String token) {
        if (token == null) {
            return false;
        }
        try {
            Jws<Claims> clamisJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * 获取token中的
     * @param token
     * @return
     */
    public static String getIdByToken(String token) {
        Jws<Claims> clamisJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        Claims claims = clamisJws.getBody();
        return (String) claims.get("userid");
    }
}
